package com.youfang.sixthmedia.ui.center;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow;
import android.widget.ViewFlipper;

import com.gzit.common.async.AsynCallback;
import com.gzit.common.async.LoadingCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.LoadingDelegater;
import com.youfang.sixthmedia.BuddyDetailActivity;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.common.BuddyAdapter;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.HeaderController;
import com.youfang.sixthmedia.message.center.GetBuddyListRequest;
import com.youfang.sixthmedia.message.center.GetBuddyListResponse;
import com.youfang.sixthmedia.message.chat.GetUnReadMsgHistoryBuddyDelegate;
import com.youfang.sixthmedia.message.model.Buddy;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnBottomListener;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnRefreshListener;

public class CBuddyActivity extends Activity {

	private int page = 1;
	private HeaderController controller;
	private GZITPullToRefreshListView listview;
	private BuddyAdapter adapter;

	private LoadingDelegater loading = new LoadingDelegater();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.c_buddy_activity);
		this.loading.init(this);

		this.listview = (GZITPullToRefreshListView) this
				.findViewById(R.id.listview);

		this.adapter = new BuddyAdapter(this);
		this.listview.setAdapter(adapter);
		this.controller = new HeaderController();
		this.controller.setup(listview, adapter);

		this.listview.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {

				remoteRefresh();

			}
		});
		this.listview.setOnBottomListener(new OnBottomListener() {

			@Override
			public void onBottomClick() {
				remoteMore();
			}

			@Override
			public void onBottom() {

			}
		});

		this.listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (YoufangContext.isLogined()) {
					Buddy buddy = (Buddy) parent.getItemAtPosition(position);
					gotoBuddyDetailActivity(buddy);
				} else {
					Net.gotoLoginActivity(CBuddyActivity.this);
				}

			}
		});

		initMenu();

	}

	private void gotoBuddyDetailActivity(Buddy buddy) {

		Intent intent = new Intent();
		intent.setClass(this, BuddyDetailActivity.class);
		intent.putExtra("data", buddy);
		this.startActivity(intent);

	}

	ViewFlipper menuFlipper;
	PopupWindow popupSave;
	View menuLayout;

	private void initMenu() {
		menuFlipper = new ViewFlipper(this);
		menuFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_in));
		menuFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_out));
		menuFlipper.setFlipInterval(600000);
		menuLayout = this.getLayoutInflater().inflate(
				R.layout.nearby_range_menu, null);
		menuFlipper.addView(menuLayout);
		// tvSave = (TextView) menuLocalSaveLayout.findViewById(R.id.save);
		// tvCancel = (TextView) menuLocalSaveLayout.findViewById(R.id.cancel);
		popupSave = new PopupWindow(menuFlipper, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupSave.setFocusable(true);
		popupSave.setBackgroundDrawable(new BitmapDrawable());
		popupSave.update();

		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				hideMenu();

			}
		};

	}

	public static void setLayoutAlpha(Activity activity, float alpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = alpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
	}

	private void hideMenu() {
		popupSave.dismiss();
		setLayoutAlpha(this, 1f);
	}

	private void showMenu() {

		if (popupSave != null) {
			if (popupSave.isShowing()) {
				popupSave.dismiss();
			} else {
				setLayoutAlpha(this, 1f);
				popupSave.showAtLocation(this.findViewById(R.id.rangeBtn),
						Gravity.BOTTOM, 0, 0);
				menuFlipper.startFlipping();// 播放动画
			}
		}

	}

	@Override
	public void onBackPressed() {
		if (this.popupSave.isShowing()) {
			setLayoutAlpha(this, 1);
			this.hideMenu();
		}
		super.onBackPressed();
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.remoteRefresh();

	}

	private void remoteLoadUnReadMsgBuddys() {
		final GetUnReadMsgHistoryBuddyDelegate delegate = new GetUnReadMsgHistoryBuddyDelegate();
		Net.message(this, delegate, new AsynCallback<Response>() {

			@Override
			public void callback(Response r) {
				if (r.isFail()) {
					return;
				}

				// get the unread message buddys...
				List<Buddy> buddys = delegate.resp.getDataList();

				if (!buddys.isEmpty()) {
					// merge the buddy status to adapter
					boolean got = false;
					for (Buddy msgB : buddys) {
						for (Buddy b : adapter.getmObjects()) {
							if (msgB.userid == b.userid) {
								b.unreadcount = msgB.unreadcount;
								b.showMessageCnt = true;
								got = true;
								break;
							}

						}
					}

					if (got) {
						adapter.notifyDataSetChanged();
					}

				}

			}
		}, LoadingCallback.EMPTY);
	}

	public void remoteRefresh() {

		// 重置页码
		page = 1;
		GetBuddyListRequest req = new GetBuddyListRequest();
		req.setPage(page);

		Net.doHttpRemote(this, req, new GetBuddyListResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onRefreshComplete();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GetBuddyListResponse resp = (GetBuddyListResponse) r;
						List<Buddy> dataList = resp.getDataList();
						adapter.reload(dataList);
						adapter.notifyDataSetChanged();
						listview.setSelection(1);
						// // 控制楼房图标
						controller.onRefresh(dataList);

						// 页码递增
						page++;

						if (dataList.isEmpty()) {
							AndroidUtils.toastShort("当前条件下没有检索到数据");
						} else {
							remoteLoadUnReadMsgBuddys();
						}

					}
				}, LoadingCallback.EMPTY);

	}

	public void remoteMore() {

		GetBuddyListRequest req = new GetBuddyListRequest();
		req.setPage(page);

		Net.doHttpRemote(this, req, new GetBuddyListResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onBottomFinish();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GetBuddyListResponse resp = (GetBuddyListResponse) r;
						List<Buddy> dataList = resp.getDataList();

						adapter.addAll(dataList);
						adapter.notifyDataSetChanged();

						// logo控制器
						controller.onMore(dataList);

						// 页码递增
						page++;

						if (!dataList.isEmpty()) {

							remoteLoadUnReadMsgBuddys();
						}

					}
				}, LoadingCallback.EMPTY);

	}

	@Override
	protected void onStop() {
		super.onStop();

	}

}
